from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView,GenericAPIView,DestroyAPIView,UpdateAPIView,ListAPIView
from .models import User, Address
from rest_framework.response import Response
from .serializers import RegisterCreateSerializer
# Create your views here.

class RegisterUsernameCountAPIView(APIView):

    def get(self,request,username):

        count = User.objects.filter(username=username).count()

        data = {
            'count':count,
            'username':username
        }

        return Response(data)

class RegisterMobileCountAPIView(APIView):

    def get(self,request,mobile):

        count = User.objects.filter(mobile=mobile).count()

        data = {
            'count':count,
            'mobile':mobile
        }

        return Response(data)


class RegisterCreateAPIView(APIView):

    def post(self,request):
        serializer = RegisterCreateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)


from .serializers import UserDetailSerializer
######################################个人中心信息获取 一级视图######################################################
# class UserDetailAPIView(APIView):
#     permission_classes = [IsAuthenticated]
#
#     def get(self,request):
#         user = request.user
#         serializer = UserDetailSerializer(user)
#         return Response(serializer.data)


######################################个人中心信息获取 三级视图######################################################
from rest_framework.generics import RetrieveAPIView
class UserDetailAPIView(RetrieveAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    def get_object(self):
        return self.request.user


######################################设置邮箱信息 一级视图######################################################
from .serializers import UserEmailSerializer
class UserEmailAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def put(self,request):
        data = request.data

        Serializer = UserEmailSerializer(instance=request.user,data=data)
        Serializer.is_valid(raise_exception=True)
        Serializer.save()

        return Response(Serializer.data)

######################################邮箱链接被激活 一级视图######################################################
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData
from mall import settings
from rest_framework import status
class UserEmailVerificationAPIView(APIView):

    def get(self,request):

        token = request.query_params.get('token')
        s = Serializer(secret_key=settings.SECRET_KEY)
        try:
            payload = s.loads(token)
        except BadData:
            return Response('token数据出错鸟',status=status.HTTP_400_BAD_REQUEST)

        id = payload.get('id')
        email = payload.get('email')

        try:
            user = User.objects.get(id=id,email=email)
        except User.DoesNotExist:
            return Response('激活链接失效', status=status.HTTP_400_BAD_REQUEST)

        user.email_active =True
        user.save()

        return Response({'message':'ok'})



##################################《《《  收货地址管理  》》》###################################################
from .serializers import UserAddressSerializer



######################################新增收货地址 一级视图######################################################
# from .models import Address
# from .serializers import UserAddressSerializer

# class UserAddressView(APIView):
#     permission_classes = [IsAuthenticated]
#
#     def post(self,request):
#
#         serializer = UserAddressSerializer(data=request.data,context={'request':request,'view':self})
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#
#         return Response(serializer.data)

######################################新增收货地址 二级视图######################################################
# class UserAddressView(GenericAPIView):
#     permission_classes = [IsAuthenticated]
#     serializer_class = UserAddressSerializer
#
#     def post(self,request):
#
#         data = request.data
#         serializer = self.get_serializer(data=data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#
#         return Response(serializer.data)

######################################新增收货地址 三级视图######################################################
class UserAddressView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = UserAddressSerializer

######################################删除、编辑收货地址 一级视图######################################################
class UserAddressModifyView(APIView):
    permission_classes = [IsAuthenticated]

    def put(self,request,pk):
        addr = Address.objects.get(id=pk)
        serializer = UserAddressSerializer(instance=addr,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    def delete(self,request,pk):
        addr = Address.objects.get(id=pk)
        addr.delete()
        return Response({'message':'删除成功'})

######################################查询收货地址 一级视图######################################################

class UserAddressInfosView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self,request):
        user = request.user
        Addr = Address.objects.filter(user=user.id).all()

        serializer = UserAddressSerializer(Addr,many=True)

        data = {
            'addresses':serializer.data,
            'limit':20,
            'default_address_id':1
        }
        return Response(data=data)

######################################设置默认收货地址 一级视图######################################################
class SetDefaultAddressView(APIView):

    def put(self,request,pk):
        user = request.user
        default_addr = Address.objects.get(id=pk)
        if not default_addr:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        user.default_address = default_addr
        user.save()

        return Response({'message':'默认地址设置成功'})


######################################历史浏览记录 一级视图######################################################
from django_redis import get_redis_connection
from goods.models import SKU
from goods.serializers import GoodsListSerializer
class BrowerHistoriesView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self,request):
        sku_id = request.data.get('sku_id')
        user_id = request.user.id
        try:
            SKU.objects.get(id = sku_id)
        except SKU.DoesNotExist:
            raise Exception('该商品不存在')

        redis = get_redis_connection('history')

        redis.lrem('history_%s'%user_id,0,sku_id)
        redis.lpush('history_%s'%user_id,sku_id)
        redis.ltrim('history_%s'%user_id,0,4)

        return Response({'message':'ok'})

    def get(self,request):
        user_id = request.user.id

        redis = get_redis_connection('history')

        histories = redis.lrange('history_%s'%user_id,0,4)
        sku =[]
        for skuid in histories:
            sku_obj = SKU.objects.get(id = skuid)
            sku.append(sku_obj)

        serializer = GoodsListSerializer(sku,many=True)

        return Response(serializer.data)




######################################登录成功后可能会存在合并本地购物车到服务器，重写生成token类######################################################

from rest_framework_jwt.views import ObtainJSONWebToken
from carts.utils import Merge_cookie_to_redis

class UserObtainJSONWebToken(ObtainJSONWebToken):

    def post(self, request, *args, **kwargs):

        response = super().post(request)

        cart_cookie = request.COOKIES.get('cart')
        if cart_cookie:
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid():
                user = serializer.validated_data.get('user')
                if user is not None and user.is_authenticated:
                    response = Merge_cookie_to_redis(user,request,response,cart_cookie)

        return response










